<template>
	<app-layout>
		<view class="goods" v-if="loading">
			
			<!-- 广告轮播图 -->
			<view class="page-width">
				<app-goods-banner
					v-bind:picList="goods_detail.pic_url"
					v-bind:videoUrl="goods_detail.video_url"
					v-bind:isCart="false"
					:goods_id="goods_id"
					sign="gift"
					:share="goods_detail.share"
				></app-goods-banner>
			</view>
			
			<!-- 商品名字 -->
			<view class="page-width name">
				<app-name
					v-bind:name="goods_detail.name"
				></app-name>
			</view>
			
			<!-- 价格参数 -->
			<view class="detail-parameter">
				<detail-parameter
					v-bind:price="goods_detail.price"
					v-bind:price_min="goods_detail.price_min"
					v-bind:price_max="goods_detail.price_max"
					v-bind:price_member_max="goods_detail.price_member_max"
					v-bind:price_member_min="goods_detail.price_member_min"
					v-bind:original_price="goods_detail.original_price"
					v-bind:sales="goods_detail.sales"
					v-bind:unit="goods_detail.unit"
					v-bind:level_show="goods_detail.level_show"
					v-bind:vip_card_appoint="goods_detail.vip_card_appoint"
					v-bind:theme="theme"
				></detail-parameter>
			</view>
			
			<!-- 加入会员 -->
			<view class="join-member" v-if="goods_detail.level_show == 2">
				<app-join-member
					v-bind:member-min-price="`${goods_detail.price_member_min}`"
					v-bind:member-max-price="`${goods_detail.price_member_max}`"
					v-bind:price="`${goods_detail.price}`"
				></app-join-member>
			</view>
			
			<!-- 超级会员卡 -->
			<view class="vip-card" v-if="goods_detail.vip_card_appoint.discount != null">
				<app-vip-card
					v-bind:isNormal="mall.setting.is_show_normal_vip == 0 ? false : true"
					top="0"
					background="#fff"
				></app-vip-card>
			</view>
			
			<!-- 商品服务 -->
			<view class="commodity-service" v-if="goods_detail.services.length > 0">
				<app-goods-service
					v-bind:list="goods_detail.services"
					v-bind:border="false"
					v-bind:setTheme="theme"
				></app-goods-service>
			</view>
			
			<!-- 规格选择 -->
			<view class="show-attr" @click="clickAttr">
				<show-attr
					v-bind:selectAttr="{attr_list: selectAttr.attr_list}"
					v-bind:attrGroups="goods_detail.attr_groups"
				></show-attr>
			</view>
			
			<!-- 商品详情 评价-->
			<view class="detailed-evaluation">
				<app-goods-detail
					v-bind:goods="goods_detail"
				></app-goods-detail>
			</view>
			
			<!-- 相关推荐 -->
			<view class="app-recommend" v-if="goods_lis.length > 0">
				<app-related-suggestion-product
						sign="gift"
					v-bind:list="goods_list"
				></app-related-suggestion-product>
			</view>
			
			<!-- 底部空格 -->
			<view class="empty">
				<app-empty-bottom v-bind:height="Number(110)"></app-empty-bottom>
			</view>
			
			<!-- 规格选择 -->
			<view class="specification-selector">
				<app-attr
					:goods="goods_detail"
					:attrGroupList="goods_detail.attr_groups"
					:show="attrShow"
					@attrtap="onAttr"
					:cartShow="false"
					:theme="theme"
					buyText="加入礼包"
					:noPay="true"
					@pay="pay"
				></app-attr>
			</view>
			
			<!-- 底部按钮 -->
			<view class="bottom-button">
				<app-iphone-x>
					<view slot="empty-area">
						<bottom-button
							v-bind:theme="theme"
                            v-bind:attr_bool="attr_bool"
							v-bind:goods_stock="goods_detail.goods_stock"
							v-on:attrSwitch="clickAttr"
							v-bind:join_disabled="join_disabled"
						></bottom-button>
					</view>
				</app-iphone-x>
			</view>
		</view>
	</app-layout>
</template>

<script>
    import { mapState } from 'vuex';
    import appGoodsBanner from '../../../components/page-component/goods/app-goods-banner.vue';
	import appName from '../../../components/page-component/app-goods-detail/app-name.vue';
	import detailParameter from '../components/goods/detail-parameter.vue';
    import appJoinMember from '../../../components/page-component/app-join-member/app-join-member.vue';
    import appGoodsDetail from '../../../components/page-component/goods/app-goods-detail.vue';
    import appVipCard from '../../../components/page-component/app-vip-card/app-vip-card.vue';
    import appRelatedSuggestionProduct from '../../../components/page-component/app-related-suggestion-product/app-related-suggestion-product.vue';
    import appGoodsService from '../../../components/page-component/goods/app-goods-service.vue';
    import appEmptyBottom from'../../../components/basic-component/app-empty-bottom/app-empty-bottom.vue';
    import appIphoneX from '../../../components/basic-component/app-iphone-x/app-iphone-x.vue';
	import bottomButton from '../components/goods/bottom-button.vue';
    import showAttr from '../../../components/page-component/goods/app-goods-attr.vue';
    import appAttr from '../../../components/page-component/app-attr/app-attr.vue';
    
    export default {
        name: 'goods',

        data() {
            return {
                // 商品ID
                goods_id: -1,
	            // 商品
	            goods_detail: {},
	            // 相关推荐
                goods_list: [],
                attr_bool: false,
	            // 选中规格
                select_data: {},
	            // 选中规格字符串
                select_str: '',
                number: 1,
                ask_gift: '',
                mch_id: -1,
                loading: false,
                join_disabled: true,
                is_share: 0,
	            is_search: 0,
                selectAttr: {},
                attrShow: 0,
            }
        },

        onLoad(options) {
            this.goods_id = options.id;
            if (options.mch_id) {
                this.mch_id = options.mch_id;
            }
            if (options.is_share == 1) {
                this.is_share = 1;
            }
            if (options.is_search == 1) {
                this.is_search = 1;
            }
            this.$store.dispatch('gift/getConfig', this.$api.gift.config);
            this.request().then(() => {
                this.requestList();
                this.requestConfig();
            });
            // 下拉刷新
            // uni.startPullDownRefresh();
        },

        onShareAppMessage() {
            return this.$shareAppMessage({
                path: '/plugins/gift/goods/goods',
                title: this.ask_gift,
                imageUrl: this.goods_detail.app_share_pic ? this.goods_detail.app_share_pic : '',
                // #ifdef MP-ALIPAY
                bgImgUrl: this.goods_detail.app_share_pic ? this.goods_detail.app_share_pic : '',
                // #endif
                params: {
                    id: this.goods_id,
	                is_share: 1,
                }
            });
        },

        methods: {
            clickAttr() {
                this.attrShow = Math.random();
            },
            onAttr(data) {
                if (data) {
                    this.selectAttr = data;
                    let attr_str = ``;
                    for (let i = 0; i < data.attr_list.length; i++) {
                        attr_str += `${data.attr_list[i].attr_group_name}: ${data.attr_list[i].attr_name} `;
                    }
                    this.select_data = {
                        name: this.goods_detail.name,
                        price: data.price,
                        attr: {
                            id: data.id,
                            attr_list: data.attr_list,
                            stock: data.stock,
                            goods_id: data.goods_id,
                        },
                        attr_str: attr_str,
                        pic_url: data.pic_url ? data.pic_url : this.goods_detail.cover_pic,
                    }
                }
            },
            // 请求商品
            async request() {
                this.$utils.showLoading();
               
                try {
                    let data = {
                        id: this.goods_id,
                    };
                    
                    // if (this.mch_id !== -1) {
                    //     url = this.$api.mch.goods_detail;
                    //     data.mch_id = this.mch_id;
                    // }

                    const res = await this.$request({
                        url: this.$api.gift.goods,
                        method: 'get',
                        data: {
                            ...data,
                        }
                    });
	                this.$utils.hideLoading();
                    if (res.code === 0) {
                        // if (this.mch_id !== -1) {
                        //     this.goods_detail = res.data.detail;
                        // } else {
                        this.goods_detail = res.data.goods;
                        // }
                        this.loading = true;
                        for (let i = 0; i < this.goods_detail.attr_groups.length; i++) {
                            for (let j = 0; j < this.goods_detail.attr_groups[i].attr_list.length; j++) {
                                if (j === 0) {
                                    this.goods_detail.attr_groups[i].attr_list[j].active = true;
                                } else {
                                    this.goods_detail.attr_groups[i].attr_list[j].active = false;
                                }
                            }
                        }
                    } else {
                        uni.showModal({
                            title: '提示',
                            content: res.msg,
                        });
                    }
                } catch (e) {
                    this.$utils.hideLoading();
                    throw new Error(e);
                }
            },
            // 请求配置
            async requestConfig() {
                this.$utils.showLoading();

                try {
                    const res = await this.$request({
                        url: this.$api.gift.config,
                        method: 'get',
                    });
                    this.$utils.hideLoading();
                    if (res.code === 0) {
                        this.ask_gift = res.data.ask_gift;
                        this.$store.commit('gift/setTheme', Number(res.data.theme.id));
                    } else {
                        uni.showModal({
                            title: '提示',
                            content: res.msg,
                        });
                    }
                } catch (e) {
                    this.$utils.hideLoading();
                    throw new Error(e);
                }
            },
	        // 请求相关推荐
	        async requestList() {
                this.$utils.showLoading();
                try {
                    const res = await this.$request({
                        url: this.$api.goods.new_recommend,
                        method: 'get',
                        data: {
                            goods_id: this.goods_id,
                            type: 'goods',
                        }
                    });
                    this.$utils.hideLoading();
                    if (res.code === 0) {
	                    this.goods_list = res.data.list;
                    } else {
                        uni.showModal({
                            title: '提示',
                            content: res.msg,
                        });
                    }
                } catch (e) {
                    this.$utils.hideLoading();
                    throw new Error(e);
                }
	        },

	        // 规格开关
            attrSwitch(data) {
                this.attr_bool = data;
            },
	        
	        pay(data) {
                console.log(this.select_data);
                this.number = data;
                if (this.$storage.getStorageSync('GIFT_CART')) {
                    let again = 0;
                    let storage = this.$storage.getStorageSync('GIFT_CART');
                    for (let i = 0; i < storage.length; i++) {
                        if (storage[i].attr.id === this.select_data.attr.id) {
                            storage[i].number += this.number;
                        } else {
                            again += 1;
                        }
                    }
                    if (again === storage.length) {
                        let data = this.select_data;
                        data.number = this.number;
                        storage.push(data);
                    }
                    this.$storage.setStorageSync('GIFT_CART', storage);
                } else {
                    let data = this.select_data;
                    data.number = this.number;
                    this.$storage.setStorageSync('GIFT_CART', [data]);
                }
                if (this.is_share === 1) {
                    uni.navigateTo({
                        url: `/plugins/gift/index/index`
                    })
                } else if(this.is_search === 1) {
                    uni.navigateBack({
                        delta: 3
                    });
                } else {
                    uni.navigateBack({
                        delta: 2
                    });
                }
	        }
        },

        computed: {
            ...mapState('gift',{
                theme: state => state.theme,
            }),
            ...mapState('mallConfig', {
                mall: state => state.mall,
            }),
        },

        components: {
            'app-goods-banner': appGoodsBanner,
	        'app-name': appName,
	        'detail-parameter': detailParameter,
	        'app-join-member': appJoinMember,
	        'app-goods-detail': appGoodsDetail,
	        'app-vip-card': appVipCard,
            'app-related-suggestion-product': appRelatedSuggestionProduct,
            'app-goods-service': appGoodsService,
            'app-empty-bottom': appEmptyBottom,
            'app-iphone-x': appIphoneX,
	        'bottom-button': bottomButton,
	        'show-attr': showAttr,
            appAttr,
        },
    }
</script>

<style lang="scss">
	@import '../css/gift';
	
	/* 商品页面 */
	.goods {
		position: absolute;
		width: 100%;
		height: 100%;
		background-color: #f7f7f7;
		
		/*加入会员*/
		.join-member {
			background-color: #ffffff;
			padding: #{0 24upx};
		}
		
		/*详情 评价*/
		.detailed-evaluation {
		
		}
		
		/*超级会员卡*/
		.vip-card {
			padding: #{0 24upx 24upx 24upx};
			background-color: #ffffff;
		}
		
		/*商品服务*/
		.commodity-service {
			margin: #{20upx 0};
		}
		
		/*规格选择*/
		.show-attr {
			margin-bottom: #{20upx};
		}
		
		/*空格*/
		.empty {}
	}
</style>